function data = cvc_export(setfiles,tail,epoevs,analysis,etxdblcols,etxstrcols)
% CVC_EXPORT
%
%  Synopsis
%  ========
%
%  data = cvc_export(setfiles,tail,epoevs,analysis,etxdblcols,etxstrcols)
%
%  -- Author: Mads Dyrholm --
%     Center for Visual Cognition, University of Copenhagen.
%     August 2011
%
%  Purpose
%  =======
%
%  Inputs
%  ======
%
%  setfiles - Cell array with full path+filenames.
%
%  tail - string to be cat to filenames before extension.
%
%  epoevs - Cell array of event names to epoch, 
%  e.g. {'Stimulus.OnsetTime'}. See cvc_eventlist(EEG)
%  for available event names.
%
%  analysis - Cell with analysis specs, the first cell 
%  defines the analysis, the following cells are options.
% 
%    {'dpss',f0,[w1 w2],NW} - e.g. {'dpss',10,[-500 0],2}
%    {'dpssica',f0,[w1 w2],NW} - e.g. {'dpss',10,[-500 0],2}
%    {'dpssica',f0,[w1 w2],0} - e.g. {'dpss',10,[-500 0],0}
%
%  etxdblcols - Cell array of etx column names to be imported
%  as doubles.
%
%  etxstrcols - Cell array of etx column names to be imported
%  as strings/categorical.


% example.
%
% data = cvc_export({'/home/mads/professor/Copenhagen/data/EEG/TCGD4pos/S1/S1_1_20SEP2010',
%		   '/home/mads/professor/Copenhagen/data/EEG/TCGD4pos/S2/S2_1_27SEP2010'}, ...
%		  '_256_1_0',{'Stimulus.OnsetTime'},...
%		  {'dpss',10,[-500 0],2},...
%		  {'TimeHigh','TimeLow','Wait','Stimulus.OnsetTime'},{'Cue'});


for subj=1:length(setfiles)
  setfile = setfiles{subj};
  [setpath,filename,ext] = fileparts(setfile);
  setfile = [filename tail '.set'];
  etxfile = fullfile(setpath,[filename '.etx']);
  tvafile = fullfile(setpath,[filename '.tva']);
  EEG = pop_loadset('filename',setfile,'filepath',setpath);
  evtypes = {};
  for nevstr=1:length(epoevs)
    evtypes = cat(2,evtypes,cvc_eventhash(EEG,epoevs{nevstr}));
  end
  
  dblcat = [];
  data = dataset;
  for edc = 1:length(etxdblcols)
    dbls = cvc_read_edat_dbl(etxfile,etxdblcols{edc});
    data = cat(2,data,dataset({dbls(:),strrep(etxdblcols{edc},'.','_')}));
  end
  strcat = [];
  for edc = 1:length(etxstrcols)
    strs = cvc_read_edat_str(etxfile,etxstrcols{edc});
    data = cat(2,data,dataset({strs(:),strrep(etxstrcols{edc},'.','_')}));
  end
  
  if size(data,1)>0
    numtrials = size(data,1);
  else
    tvadata = tvaloader(tvafile);
    numtrials = length(tvadata);
  end

  switch analysis{1}
   case 'dpss'
    dpsswindow=analysis{3};
    epochwindow = (dpsswindow + [-1000/EEG.srate 1000/EEG.srate]) /1000
    f0s = analysis{2};
    NW = analysis{4};
   case 'er'
    epochwindow = analysis{2};
   otherwise
    error('Unknown analysis option.');
  end
  
  EEG = pop_epoch( EEG, evtypes, epochwindow, 'newname', 'EPO', 'epochinfo', 'yes');
  %  EEG = pop_rmbase( EEG, [1  500]);
  EEG = eeg_checkset( EEG );
  %sjovchans = eeg_chaninds(EEG,'H28')
    
  [trials,epoev] = cvc_eeg_epoch_to_edat_trial(EEG);
  for trial=1:numtrials, epoch_event{trial,1} = '-'; end
  for epo=1:length(epoev)
    tmp = cvc_eventhash(EEG,epoev(epo));
    epoch_event(trials(epo)) = tmp;
  end
  data=cat(2,dataset({epoch_event,'Epoch_event'}),data);
  
  
  tmp = nan(numtrials,1);
  tmp(trials) = 1:length(trials);
  data=cat(2,dataset({tmp,'Epoch'}),data);
  tmp(:) = 1:length(tmp);
  data=cat(2,dataset({tmp,'Trial'}),data);
  
  tmp = {}; for trial=1:numtrials, tmp{trial,1} = filename; end
  data=cat(2,dataset({tmp,'EEG_file'}),data);
  
  switch analysis{1}
   case 'dpss'
    eegchans = eeg_chantype(EEG,'EEG');
    [BW,rawpowChan,filtpowChan] = cvc_erpower(EEG,dpsswindow(1),dpsswindow(2),NW,f0s,eegchans);
    for chan=1:length(eegchans)
      tmp = nan(numtrials,1);
      tmp(trials) = filtpowChan(chan,:);
      data = cat(2,data,dataset({tmp,EEG.chanlocs(chan).labels}));
    end
   case 'dpssica'
    EEG.icaact = eeg_getica(EEG);
    comps = 1:size(EEG.icaweights,1);
    if NW>0
      [BW,rawpowComp,filtpowComp] = cvc_erpower(EEG,dpsswindow(1),dpsswindow(2),NW,f0s,-comps);
    else
      [BW,rawpowComp] = cvc_erpower(EEG,dpsswindow(1),dpsswindow(2),1,f0s,-comps);
      filtpowComp = rawpowComp;
    end
    for comp=1:length(comps)
      tmp = nan(numtrials,1);
      tmp(trials) = filtpowComp(comp,:);
      data = cat(2,data,dataset({tmp,['Ica' num2str(comp)]}));
    end
  end
  
  alldata{subj} = data;
  
end

% vert cat setfiles
allvars = {};
for subj=1:length(alldata)
  tmp = get(alldata{subj});
  allvars = union(allvars,tmp.VarNames);
end

for subj=1:length(alldata)
  data1 = alldata{subj};
  tmp = get(data1);
  missingvars = setdiff(allvars,tmp.VarNames);
  tmp = nan(numtrials,1);
  for idx=1:length(missingvars)
    data1 = cat(2,data1,dataset({tmp,missingvars{idx}}));
  end
  if subj == 1
    data = data1;
  else
    data = vertcat(data,data1);
  end
end

